/**
 * =====================================================
 * 游戏运算类
 * 设置房间属性：
 * 		players		Array	参与游戏玩家数组
 * 		pubPoker	Array	公共牌
 * 		sendPub		Number 	已发送的公共牌数
 * 		betNum		Number  第几次下注圈
 * 		userPoker	Object  玩家私有牌，索引为玩家座位号
 * 		banker		Number	庄家座位号
 * 		action		Number 	当前叫牌玩家座位号
 * 		pot			Array	池底对象数组
 * 		fold		Array	某个下注圈弃牌的玩家
 * 		callers		Array	某个下注圈下注的玩家 [{sit,chip},{sit,chip},...]
 * 		betChip		Object	玩家下注筹码数,索引为玩家座位号
 *      raiseSit	Number  下注圈中最大加注的玩家座位号
 * 		maxChip		Number  下注圈最大下注码
 * 
 * ===================================================== 
 */


/**
 * 游戏操作
 * 
 */
function gameEvent() { }

/**
 * 調用本類的實例方法
 * @param	r_room	房間對象
 * @param	r_user	操作者
 * @param	r_type	操作類型
 * @param	r_param	参数
 * @return	
 */
gameEvent.prototype.handleFun = function(r_room, r_user, r_type, r_param) {			
	if ( r_type != '' ) {					
		return this[r_type](r_room, r_user, r_param);
	}
}

/**
 * 游戏开始，执行初始化
 * @param 
 */
gameEvent.prototype.gameStart = function(r_room)
{			
	__debug.trace("gameStart room :" + r_room.getId());	
	send("start", { }, r_room.getAllUsers());
	
	var _poker = new poker();	//实例化扑克牌	
	_poker.remove([ { 'label':'BLACK_JOKER', 'value':0, 'suit':'NULL' }, { 'label':'RED_JOKER', 'value':0, 'suit':'NULL' } ]); //移除大鬼，小鬼
	_poker.shuffle();  //洗牌	
	var _public_poker = _poker.deal(5);	//公共牌
		
	var _pro_obj = { };
	_pro_obj["players"]   = this.getPlayers(r_room);
	_pro_obj["pubPoker"]  = _public_poker
	_pro_obj["sendPub"]   = 0;	
	_pro_obj["action"]    = 0;
	_pro_obj["pot"]   	  = [];	
	_pro_obj["maxChip"]   = 0;
	_pro_obj["fold"]   	  = [];	
	_pro_obj["callers"]   = this.getPlayers(r_room);
	_pro_obj["betChip"]	  = { };
	_pro_obj["betNum"]    = 1;
	__roomVars.setProListVar(r_room, _pro_obj);
	
	
	this.sortCallers(r_room);
	
	//__debug.trace("action : " + __roomVars.getProVar(r_room, "action"));
	var _users_poker = this.deal(r_room, _poker);  			//发家私有牌		
		
	//游戏初始，设置叫牌玩家
	//this.startCall(r_room);			
	
	//发送庄家
	var _data = { banker:this.getBanker(r_room)};
	send("banker", _data, r_room.getAllUsers());		
	
	//發送大小盲注
	var _min_blind = __roomVars.getVar(r_room, "minBlind", "int");	//小盲注
	var _max_blind = __roomVars.getVar(r_room, "maxBlind", "int");	//大盲注
	var _banker_sit = this.getBanker(r_room);	//庄家位置		
	var _callers = __roomVars.getProVar(r_room, "callers");	
	this.userBet(r_room, _callers[0], _min_blind, 5);
	_callers = __roomVars.getProVar(r_room, "callers");	
	this.userBet(r_room, _callers[0],_max_blind, 5);
	this.sendAction(r_room);	
	
	//发送玩家私有牌数据
	var _uid;
	for (var _sit in _users_poker){
		_user = r_room.getUserByPlayerIndex(_sit);
		var _data = { poker:this.formatPoker(_users_poker[_sit]), uid: __userVars.getVar(_user, "userId", "int") };
		send("deal", _data, [_user]);
	}
	
	
}

/**
 * 将游戏玩家按叫牌顺序排序
 * 庄家为最后一位叫牌,庄家座位前一位(小盲注)第一个叫牌
 */
gameEvent.prototype.sortCallers = function(r_room) {	
	var _players = __roomVars.getProVar(r_room, "callers");  
	var _banker_sit = this.getBanker(r_room);
	var _sit = 0;
	var _callers = [];
	for each(var _user in _players) {
		_sit = _user.getPlayerIndex();
		if (_sit < 1) continue;	
		if (_sit > 9) continue;		
		_callers.push(_sit);		
	}	
	_callers = arraySort(_callers, "asc"); //排序	
	var _cut = _banker_sit ;	
	var _upside = [];
	var _offside = [];		
	for each(var _sit in _callers) {
		if (_sit > _cut) {
			_upside.push(_sit);
		}else {
			_offside.push(_sit);
		}
	}
	_callers = _upside.concat(_offside);		
	__roomVars.setProVar(r_room, "callers", _callers);
	//__roomVars.setProVar(r_room, "action", parseInt(_callers[0]));
}

/**
 * 发玩家私有牌
 * @param r_room
 */
gameEvent.prototype.deal = function(r_room, r_poker)
{
	var _players = __roomVars.getProVar(r_room, "players");  //游戏玩家
	var _sit;
	var _users_poker = {};
	for each(var _user in _players) {		
		_sit = _user.getPlayerIndex();		     		//获取玩家座位号
		if(_sit > 0){
			_users_poker[_sit] = r_poker.deal(2); 		//從撲克實例中取出兩張撲克牌			
		}
	}
	__roomVars.setProVar(r_room,"userPoker", _users_poker);	 //保存玩家私有牌	
	__roomVars.setProVar(r_room,  "userPoker",_users_poker );
	return _users_poker;
}

/**
 * 发送公共牌
 * @param r_room
 */
gameEvent.prototype.handPublicPoker = function(r_room) {	
	var _public_poker = __roomVars.getProVar(r_room,"pubPoker"); 	 
	var _send_num = __roomVars.getProVar(r_room, "sendPub");  
	var _poker = [];
	if (_send_num == 0) {
		_poker = _public_poker.slice(0, 3);
		_send_num = 3;
	}else if(_send_num <5){
		_poker = _public_poker.slice((_send_num - 1), 1);
		_send_num++;
	}
	_poker = this.formatPoker(_poker);	//格式化扑克数据，用于传输
	__roomVars.setProVar(r_room, "sendPub", _send_num);	
	send("comCards", _poker, r_room.getAllUsers());	
}

/**
 * 获取玩家扑克
 * @param r_room
 * @param r_user
 */
gameEvent.prototype.getUserPoker = function(r_room, r_user) {	
	var _poker_list = __roomVars.getProVar(r_room, "userPoker");  
	var _sit = r_user.getPlayerIndex();
	var _poker = _poker_list[_sit] ? _poker_list[_sit] : [];
	return _poker;
}

/**
 * 设置庄家,第一局游戏开始，第一个坐下的玩家为庄家
 * @param r_room
 * @param r_user
 */
gameEvent.prototype.checkBanker = function(r_room, r_user) {	
	__roomVars.setProVar(r_room, "banker", r_user.getPlayerIndex());	
}

/**
 * 获取庄家座位号
 * @param r_room
 * @return int
 */
gameEvent.prototype.getBanker = function(r_room) {
	var _banker = __roomVars.getProVar(r_room, "banker");  
	return parseInt(_banker);
}

/**
 * 获取游戏玩家
 * @param r_room
 */
gameEvent.prototype.getPlayers = function(r_room) {
	if ( __roomVars.getProVar(r_room, "players")) {
		return __roomVars.getProVar(r_room, "players");   
	}
	var _players = r_room.getAllPlayers();  	//獲取游戲玩家
	var _res = [];
	var _u;	 
	for each(_u in _players) {		
		if(__userVars.getState(_u) == "play"){
			_res.push( _u );			
		}
	}	 		
	__roomVars.setProVar(r_room,"players", _res);	
	__debug.trace(" Players :" + _res.length)
	return _res;
}

/**
 * 移除游戏中玩家
 * @param r_room
 * @param r_players Array 
 */
gameEvent.prototype.removePlayers = function(r_room,r_players)
{	
	var _user;
	var _index;
	var _user_list = this.getPlayers(r_room);	
	for each(_user in r_players) {
		_index = _user_list.indexOf(_user);
		if (_index > -1) {
			delete _user_list[_index];
			__debug.trace("remove player : " + _user);
		}
	}
}
 
/**
 * 根据给定的玩家，获取其下位玩家
 * @param r_room
 * @param r_sit int 
 * @param r_step 跳步,获取 r_sit 后第几位玩家
 */
gameEvent.prototype.getNextPlayer = function(r_room, r_sit, r_step) {
	var _user;			
	r_step = parseInt(r_step) == NaN ? 1 : parseInt(r_step);		
	var _len = this.getPlayers(r_room).length;
	if (r_step > _len) {
		r_step = r_step % _len;
	}	
	var _start = r_sit +1;
	var _arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
	var _tmp = _arr.splice(r_sit);
	_arr = _tmp.concat(_arr);
	for each(var i in _arr) {
		_user = r_room.getUserByPlayerIndex(i);		
		if (_user) {			
			if (r_step == 1) {				
				return _user;
				break;
			}
			r_step--;
		}
	}
	return _user;
}

/**
 * 
 */
gameEvent.prototype.checkBetType = function(type,r_chip)
{
	
}

/**
 * 玩家下注
 * @param r_room
 * @param r_user
 * @param r_type  int 下注类型
 */
gameEvent.prototype.userBet = function(r_room, r_sit, r_chip, r_type) {	
	var _callers = __roomVars.getProVar(r_room, "callers");					
	var _sit = r_sit; 			
	if (_sit != _callers[0]) return; 	
	_callers.splice(0, 1);
	_callers.push(_sit);
	__roomVars.setProVar(r_room, "callers",_callers);
	var _user = r_room.getUserByPlayerIndex(_sit);
	if(r_type == 5){
		var _sendAction = false;
	}else {
		var __sendAction = true;
	}			
	var _maxChip = __roomVars.getProVar(r_room, "maxChip");	//当前最大下注
	var _betChip = __roomVars.getProVar(r_room, "betChip");
	var _my_chip = __userVars.getVar(_user, "chip","int");
 	var _befor_bet = parseInt(_betChip[_sit]);
	var _sub = 0;
	if (r_type == 1) { //看牌
		this.next(r_room);
		return;
		
	}else if (r_type == 2) { //跟注
		_sub = _maxChip - befor_bet;
		
	}else if (r_type == 3) {//加注				
		if (r_chip > _my_chip) r_chip = _my_chip;				
		if (r_chip < _maxChip) r_chip = _maxChip;				
		_sub = r_chip - befor_bet;
		
	}else if (r_type == 4 ) {//弃牌
		//弃牌.......
		return;
	}
	var _remain = __userVars.subtractChip(_user, _sub); //扣除玩家筹码			
	_betChip[_sit] = r_chip;
	__roomVars.setProVar(r_room, "betChip", _betChip);	//记录玩家下注筹码
		
	if (_remain == 0) {		
		r_type = 3; //全下
	}			
	
	//判断是否为加注	
	if (r_chip > _maxChip) {	
		__roomVars.setProVar(r_room, "maxChip", r_chip);
		__roomVars.setProVar(r_room, "raiseSit", _sit);	
		r_type = 1;
	}				
	
	//发送数据
	var _data = { };
	_data["uid"]  = __userVars.getVar(_user, "userId", "int");	
	_data["way"]  = r_type;
	_data["chip"] = r_chip;
	_data["bank"] = _remain;		
	send("bet", _data, r_room.getAllUsers());	
	
	if (__sendAction) {
		this.sendAction(r_room);
	}
}

/**
 * 下一叫牌，如果当轮下注圈结束，发送公共牌，从小盲注开始叫牌
 * @param r_room
 */
gameEvent.prototype.sendAction = function(r_room) {		
	var _callers = __roomVars.getProVar(r_room, "callers");
	var _max_chip = __roomVars.getProVar(r_room, "maxChip");
	var _next_sit = _callers[0];
	if (_next_sit > 0 ) {
		var _user = r_room.getUserByPlayerIndex(_next_sit);
		var _uid = parseInt(__userVars.getVar(_user, "userId"));
		send("action", { uid:_uid, chip:_max_chip },r_room.getAllUsers() );
	}
}

gameEvent.prototype.check

/**
 * 發送叫牌玩家座位號,跟注籌碼
 */
gameEvent.prototype.sendCall = function(r_room) {
	
}

gameEvent.prototype.sendPot = function(r_room) {
	
}


/**
 * 记录当前最大下注玩家、筹码
 */
gameEvent.prototype.recordMaxChip = function (r_room,r_user,r_chip)
{
	var _maxChip = r_room.properties.get("maxChip");
	var _sit = r_user.getPlayerIndex();
	if (_maxCihp <= 0 ) {
		r_room.properties.put("maxChip", r_chip);		
		r_room.properties.put("raiseSit", _sit);
	}else {
		if (r_chip > _maxChip) {
			r_room.properties.put("maxChip", r_chip);
			r_room.properties.put("raiseSit", _sit);
		}
	}
}

/**
 * 玩家超时处理
 * @param r_params  {room, user}
 */
gameEvent.prototype.timeoutHandler = function(r_params) {
	var _room = r_params["room"];
	var _user = r_params["user"];
	var _state = __userVars.getState(_user);
	if (_state == "play") {
		this.removePlayers(_room, [_user]);		
	}
		
}

/**
 * 格式化扑克牌，用于传输
 * @param r_poker 	{} | [{},{},...]
 */
gameEvent.prototype.formatPoker = function(r_poker) {
	var _poker_type = { SPADE:0, HEART:1, CLUB:2, DIAMOND:3 };
	var _new_poker = [];				
	if ( r_poker.length == undefined) {
		_new_poker.push(r_poker['label'] + "," + _poker_type[r_poker['suit']]);						
	}else {
		for each(var _poker in r_poker) {
			_new_poker.push(_poker['label'] + "," + _poker_type[_poker['suit']]);						
		}
	}
	return _new_poker;			
}

/**
 * 生成池底
 */
gameEvent.prototype.creatPot = function(r_room) {
	
}

/**
 * 检查游戏是否结束
 * 游戏进行中的异常操作(站起\离开\断线等)需调用该方法
 */
gameEvent.prototype.checkGame = function(r_room) {
	
	
}

/**
 * 游戏结束,发送结果
 * 
 */
gameEvent.prototype.gameOver = function(r_room) {
	__roomVars.setProVar(r_room, "action", 0);	
}
/**
 * 任务计时器
 * @param r_time int 时间
 * @param r_fun Function
 * @param r_param  Object  要传递给 f_fun 的参数
 * @param r_pool 是否循环执行
 */
gameEvent.prototype.setInterval = function(r_room, r_time, r_fun, r_param, r_pool)
{
	var _taskid = r_room.getId();
	__schControler.addScheduledTask(_taskid, r_time, false, r_fun, r_param, this);
}

